package util;

import com.google.gson.*;

import java.util.ArrayList;
import java.util.List;

public class JsonTransformation {//json转换,以实体Manager为例
    static byte[] textByte = new byte[0];
    static String endodeStr;
    static String decodeStr;

    public static <T> String objectToJson(T clazz)//object to json
    {
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
        endodeStr = gson.toJson(clazz);
        return endodeStr;
    }

    public static <T> T jsonToObject(String gsonStr, Class<T> clazz)//json to object
    {
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
        return gson.fromJson(gsonStr, clazz);
    }

    public static <T> String listToJson(List<T> list)//list to json
    {

        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
        endodeStr = gson.toJson(list);
        return endodeStr;
    }


    public static <T> List<T> jsonToList(String gsonStr, Class<T> clazz)//json to list
    {
        List<T> list = new ArrayList<T>();
        try {
            Gson gson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd HH:mm:ss")
                    .create();
            JsonArray arry = new JsonParser().parse(gsonStr).getAsJsonArray();
            for (JsonElement jsonElement : arry) {
                list.add(gson.fromJson(jsonElement, clazz));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;

    }


}
